package com.goldenlight.fvms.manager.websocket;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@ServerEndpoint(value = "/testWebsocket/{username}")
@Component
@Slf4j
public class ExcelUploadWebSocketServer {
    private static Logger logger = LoggerFactory.getLogger(ExcelUploadWebSocketServer.class);
    private static Map<String, Session> sessionPool = new HashMap<>();
    private static Map<String, String> sessionIds = new HashMap<>();
    private Session session;

    private static volatile String state = "";
    private static Lock lock = new ReentrantLock();
    private static Condition condition = lock.newCondition();

    public static String getState() {
        lock.lock();
        try {
            while (StringUtils.isEmpty(state)) {
                logger.info("await msg");
                condition.await();
            }
            logger.info("get messge");

            return state;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            lock.unlock();
        }
        return state;
    }

    public static void setState(String state) {
        lock.lock();
        try {
            ExcelUploadWebSocketServer.state = state;
            condition.signalAll();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }finally {
            lock.unlock();
        }

    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "username") String username) {
        this.session = session;
        sessionPool.put(username, session);
        sessionIds.put(session.getId(), username);
        logger.info("有连接接入");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        sessionPool.remove(sessionIds.get(session.getId()));
        sessionIds.remove(session.getId());
        logger.info("有连接关闭");
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        logger.info("来自客户端的消息：{}", message);
        if (StringUtils.isEmpty(message)) {

        } else {
            if (message.equals("ok")) {
                //确认导入
                setState("ok");
            } else {
                //取消导入
                setState("cancel");
            }
        }

    }

    /**
     * 出现错误
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("发生错误：{}，Session ID： {}", error.getMessage(), session.getId());
        log.error(error.getMessage(), error);
    }


    public static void sendMessage(String message, String username) {
        logger.info("send message:{}", message);
        Session s = sessionPool.get(username);
        if (s != null) {
            try {
                s.getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

}
